package com.example.jiaoyidui;

import com.alibaba.excel.util.FileUtils;
import com.example.jiaoyidui.component.Handler;
import com.example.jiaoyidui.component.SystemProperties;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author Alan
 * @Date 2021/10/27 16:24
 */
@Controller
@RequestMapping("/data")
@Slf4j
public class IndexController {
    volatile boolean ing = false;
    String lock = "lock";
    @GetMapping("/begin")
    public String begin(@RequestParam("times") String times, @RequestParam("chainCode") String chainCode) {
        log.info(times + "    " + chainCode);
        synchronized (lock) {
            if (ing) {
                return "fail";
            } else {
                ing = true;
            }
        }
        new Handler().begin(Integer.parseInt(times), chainCode);
        ing = false;
        return "suc";
    }

    @RequestMapping("/goFile")
    public String goFile(Model model, HttpServletRequest request) {
        File dir = new File(SystemProperties.USER_DIR + "/excel/");
        List<File> listFile = new ArrayList<>();
        //String url = request.getScheme() +"://" + request.getServerName()  + ":" +request.getServerPort() +request.getContextPath();
        Arrays.stream(dir.listFiles()).forEach(f -> {
            log.info(f.getName());
            listFile.add(f);
        });
        model.addAttribute("files", listFile);
        return "files";
    }

    @RequestMapping("/down/{name}")
    public void down(@PathVariable("name") String fileName, HttpServletResponse response) {
        log.info("down fileName is {}", fileName);
        File file = new File(SystemProperties.USER_DIR + "/excel/" + fileName);
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            out = response.getOutputStream();
            out.write(FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}